package cn.hyh.core.component;

import cn.hyh.core.vo.ResultVo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @auther :hyh
 * @desc :
 * @date :2019/7/22
 */

@RestControllerAdvice
public class CatchExceptionHandler {

    @ExceptionHandler(value = CanTellUserException.class)
    public Object CanTellUserExceptionHandler(HttpServletRequest request, HttpServletResponse response,Exception e) throws IOException {
        StackTraceElement[] stackTrace = e.getStackTrace();
        if (stackTrace != null && stackTrace.length > 0) {
            StackTraceElement errorElement = stackTrace[0];
            StringWriter stringWriter = new StringWriter();
            PrintWriter writer = new PrintWriter(stringWriter);
            e.printStackTrace(writer);
            System.out.println(stringWriter.toString());
            //关闭。
            stringWriter.close();
            writer.close();

        }
        return ResultVo.errorToUser(e.getMessage());
    }


    @ExceptionHandler(value = Exception.class)
    public Object ExceptionHandler(HttpServletRequest request, HttpServletResponse response,Exception e) throws IOException {
        StackTraceElement[] stackTrace = e.getStackTrace();
        if (stackTrace != null && stackTrace.length > 0) {
            StackTraceElement errorElement = stackTrace[0];

            System.out.println("出错文件===》"+errorElement.getFileName());
            System.out.println("出错方法===》"+errorElement.getMethodName());
            System.out.println("出错行数===》"+errorElement.getLineNumber());

            StringWriter stringWriter = new StringWriter();
            PrintWriter writer = new PrintWriter(stringWriter);
            e.printStackTrace(writer);
            System.out.println(stringWriter.toString());
            //关闭。
            stringWriter.close();
            writer.close();
        }
        return ResultVo.failResultMsg(e.getMessage());
    }
}
